﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace CallWebApiFromClient
{
    public class Class1
    {

        private void CallXloboApi2NotifyBillGot(int tmallReminderId, string txLogisticId, string statusName)
        {
            var client = new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings["xloboapi"]) };

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var request = BuildNotifyBillGotRequest(txLogisticId, statusName);


            var url = ConfigurationManager.AppSettings["xloboapi"] + "api/XloboNotifyTmall/NotifyBillGot";

            var response = client.PostAsJsonAsync(url, request);



            var responseResult = response.Result.Content.ReadAsAsync<NotifyBillGotResult>().Result;

            if (responseResult.Success)
            {
                //SetReminderNotified(tmallReminderId);
                //ApplicationLog.Info(string.Format("tmallreminderId:{0}通知揽收成功", tmallReminderId));
                ////result.AddError(responseResult.Errors[0]);
            }
            else
            {
                //ApplicationLog.Info(string.Format("tmallreminderId:{0}通知揽收失败", tmallReminderId));
            }
        }


        private XloboApiRequest BuildNotifyBillGotRequest(string txLogisticId, string statusName)
        {
            var gotMsg = new NotifyBillGotMessage()
            {
                txLogisticId = txLogisticId,
                StatusName = statusName,
            };

            var queryjson = ToJson(gotMsg);


            var digest = SignMD5(queryjson, GetCallSecret());


            var request = new XloboApiRequest()
            {
                logistics_interface = queryjson,
                data_digest = digest
            };
            return request;
        }


        private string GetCallSecret()
        {
            return ConfigurationManager.AppSettings["callXloboApiSecret"];
        }


        public static string SignMD5(string parameterStr, string secret)
        {

            var query = new StringBuilder();
            query.Append(parameterStr);
            query.Append(secret);

            // 第三步：使用MD5加密
            var md5 = MD5.Create();
            byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));

            // 第四步：把二进制转化为大写的十六进制
            var result = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                string hex = bytes[i].ToString("X");
                if (hex.Length == 1)
                {
                    result.Append("0");
                }
                result.Append(hex);
            }

            return result.ToString();
        }

        public static string ToJson(object obj)
        {
            var json = new JavaScriptSerializer().Serialize(obj);
            return json;
        }

    }

    internal class NotifyBillGotResult
    {
        public bool Success { get; set; }
    }


    internal class XloboApiRequest
    {
        /// <summary>
        /// 消息内容
        /// </summary>
        public string logistics_interface { get; set; }

        /// <summary>
        /// 消息签名
        /// </summary>
        public string data_digest { get; set; }

    }
    
    internal class NotifyBillGotMessage
    {
        public string txLogisticId { get; set; }
        public string StatusName { get; set; }
    }


       
}
